package ch02.demo;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;

public class demo4 {
    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse("src/ch02/demo/demo.xml");
        Element brandElement = doc.createElement("Brand");
        brandElement.setAttribute("name", "三星");

        Element typeElement = doc.createElement("Type");
        typeElement.setAttribute("name", "NoteX");
        //添加父子关系
        brandElement.appendChild(typeElement);
        Element phoneElement = (Element) doc.getElementsByTagName("PhoneInfo").item(0);
        phoneElement.appendChild(brandElement);
        //保存XML文件
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource domSource = new DOMSource(doc);
        //设置编码类型
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        StreamResult result = new StreamResult(new FileOutputStream("src/ch02/demo/demo.xml"));
        transformer.transform(domSource, result);
    }
}

